$(document).ready(function(){
	// hide #back-top first
	$('#back-top').hide();
	$('#form-comment').hide();
	$('.button_comment').hide();

	var arrayIdReplyComment = [];
	var count = 0,
		isActiveComment = false;
	var errorsText = '';
	var urlOrigin = window.location.origin;

	$('.reply_Comment').each(function(){
		arrayIdReplyComment[count ++] = false;
	});
	// fade in #back-top
	$(function () {
		$(window).scroll(function () {
			if ($(this).scrollTop() > 500) {
				$('#back-top').fadeIn();
			} else {
				$('#back-top').fadeOut();
			}
		});

		// scroll body to 0px on click
		$('#back-top a').click(function () {
			$('body,html').animate({
				scrollTop: 0
			}, 800);
			return false;
		});

		$('#scroll_Comments').click(function () {
			$('html, body').animate({
                scrollTop: $("#load_Comment").offset().top
            }, 800);
		});
		
	});

	$(".productPriceWrapRight a div").click(function() {
		var productIDValSplitter 	= (this.id).split("_");
		var productIDVal 			= productIDValSplitter[1];
		var productX 		= $("#productImageWrapID_" + productIDVal).offset().left;
		var productY 		= $("#productImageWrapID_" + productIDVal).offset().top;
		if( $("#productID_" + productIDVal).length > 0){
			var basketX 		= $("#productID_" + productIDVal).offset().left;
			var basketY 		= $("#productID_" + productIDVal).offset().top;			
		} else {
			var basketX 		= $("#basketTitleWrap").offset().left;
			var basketY 		= $("#basketTitleWrap").offset().top;
		}
		var gotoX 			= basketX - productX;
		var gotoY 			= basketY - productY;
		var newImageWidth 	= $("#productImageWrapID_" + productIDVal).width() / 3;
		var newImageHeight	= $("#productImageWrapID_" + productIDVal).height() / 3;
		var pathImgLoader = "<img src='" + urlOrigin+ "/public/frontend/images/ajax-loader.gif'>";
		$("#productImageWrapID_" + productIDVal + " img")
		.clone()
		.prependTo("#productImageWrapID_" + productIDVal)
		.css({'position' : 'absolute'})
		.animate({opacity: 0.4}, 100 )
		.animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() {
			$(this).remove();
			$("#notificationsLoader").html(pathImgLoader);

			$.ajax({ 
				type: "POST", 
				headers: { 'Access-Control-Allow-Origin': '*' },
       			crossDomain: true,
				url: urlOrigin+ "/cart/addCartProduct",  
				data: { productID: productIDVal},  
				success: function(theResponse) {
					setTimeout(
					function()
					{
						$("#basketItemsWrap").html(theResponse);
						$("#basketItemsWrap tr:nth-child(2)").hide();
						$("#basketItemsWrap tr:nth-child(2)").show("slow");  
						$("#notificationsLoader").empty();
					}, 500);
					
				}  
			});
			
		
		});
		
	});

	$(".product").hover(function(){
		this.style.borderColor = '#efefef';
		//this.style.background = '#f3f5f5'
	  },function(){
	  	this.style.borderColor = 'white';
	  	//this.style.background = 'white'
	});

	$('#form input').keydown(function(e) {
	    if (e.keyCode == 13) {
	        //$('#form').submit();
	        alert('Wating for Implement...');
	    }
	});

	$( "#dialogEmptySearch" ).dialog({
		autoOpen: false,
		modal: true,
		width: 400,
		buttons: [{
				text: "Ok",
				click: function() {
					$( this ).dialog( "close" );
				}
			}
		]
	});

    $("img.lazy").lazyload({
		effect:"fadeIn"
	});


	$('#button_comment').click(function() {
		if(isActiveComment) {
			$('#form-comment').hide("slow");
			this.textContent = 'Add Comment';
			isActiveComment = false;
		}
		else {
			$('#form-comment').show("slow");
			this.textContent = 'Close Comment';
			isActiveComment = true;
		}
	});

	$('.complete_comment .btn-success').click(function() {
		var commentIDValSplitter 	= (this.id).split("_");
		var commentIDVal 			= commentIDValSplitter[commentIDValSplitter.length - 1];
		errorsText = '<p>';
		var cm_Name = $('#cm_Name').val(),
			cm_Email = $('#cm_Email').val(),
			cm_Content = $('#cm_Content').val(),
			valid1 = true,
			valid2 = true,
			valid3 = true,
			cm_Id = commentIDVal,
			product_Id = this.value,
			cm_IsMember = $('#ck_isMember').is(":checked"),
			isLogin = $('#ck_isMember')[0].value == '' ? false : true;

		valid3 = checkEmpty(cm_Content, 'Content');

		if(!isLogin) {
			valid1 = checkRegexp(cm_Email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
			valid2 = checkEmpty(cm_Name, 'Name');
		}
		if(!(valid1 && valid2 && valid3)) {
			$('#showValidateComment').avgrund({
				height: 150,
				holderClass: 'custom',
				showClose: true,
				showCloseText: 'X Close',
				enableStackAnimation: true,
				onBlurContainer: '.container',
				template: errorsText + '</p>' +
				'<div>' +							
				'<a href="#" target="_blank" class="twitter">Đóng</a>' +							
				'</div>'
			});
			$('#showValidateComment').trigger('click');
		} else {
			$.ajax({ 
				type: "POST", 
				headers: { 'Access-Control-Allow-Origin': '*' },
	   			crossDomain: true,
				url: urlOrigin+ "/comment/addComments",  
				data: {
					cm_Name: cm_Name,
					cm_Content: cm_Content,
					cm_Email: cm_Email,
					cm_Id: cm_Id,
					cm_Product_Id: product_Id,
					cm_IsMember: cm_IsMember,
					cm_isLogin: isLogin

				},  
				success: function(theResponse) {
					$('#load_Comment').html(theResponse);
					$('#cm_Name').val('')
					$('#cm_Email').val(''),
					$('#cm_Content').val('');
				},
				error: function(theResponse) {
				}  
			});
		}
	})

	
	$('.reply_Comment').click(function() {
		var commentIDValSplitter 	= (this.id).split("_");
		var commentIDVal 			= commentIDValSplitter[commentIDValSplitter.length - 1];
		var form_comment  = '#form_comment_' + commentIDVal;
		var button_comment = '#button_comment_' + commentIDVal;
		var me = this;
		var squenceRelyComment=parseInt(this.getAttribute('value'));
		var flag_1 = false;
		setTimeout(function() {
			$('.table_form_comment').remove();
			$('.button_comment').hide();
		});
		// function reset

		for(var i = 0; i < arrayIdReplyComment.length ; i ++) {
			if(arrayIdReplyComment[i] && (i !== squenceRelyComment)) {
				arrayIdReplyComment[i] = false;
			}
		}

		$('.reply_Comment').each(function(){
			if(this.id == "reply_Comment_0") {
				this.childNodes[1].innerText = 'Add Comment';
			} 
			else {
				this.childNodes[1].innerText = 'Reply';
			}
		});


		if(!arrayIdReplyComment[squenceRelyComment]) {
			
			$.ajax({ 
				type: "Get", 
				headers: { 'Access-Control-Allow-Origin': '*' },
	   			crossDomain: true,
				url: urlOrigin + "/comment/getFormComments", 
				success: function(theResponse) {
					
					$(form_comment).html(theResponse);
					$(form_comment).hide();
					$(form_comment).show("slow");
					$(button_comment).show();
					me.childNodes[1].innerText = 'Close Comment';
					arrayIdReplyComment[squenceRelyComment] = true;
				},
				error: function(theResponse) {
				}  
			});
		}
		else {
			arrayIdReplyComment[squenceRelyComment] = false;
			if(me.id == "reply_Comment_0") {
				me.childNodes[1].innerText = 'Add Comment';
			} 
			else {
				me.childNodes[1].innerText = 'Reply';
			}
			$('.button_comment').hide();
		}
	});

	

	function checkRegexp( o, regexp) {
		if (!(regexp.test(o))) {
			errorsText += 'Email không đúng định dạng.  </br>';
			console.log(errorsText);
			return false;
		} else {          
			return true;
		}
	}

	function checkEmpty(value, field) {
		if(value.length == 0) {
			errorsText += field + ' không được phép rỗng.</br>';
			return false;
		}
		else {
			return true
		}
	}
});
	
function submitSearch() {
	var textSeach = $('#KeyName').val();
	if(textSeach === 'Nhập Từ Khóa' || textSeach ==='') {
		errorsText = '<p>Bạn hãy nhập thông tin tìm kiếm. </p>';
		$('#showEmptyTextSearch').avgrund({
			height: 100,
			holderClass: 'custom',
			showClose: true,
			showCloseText: 'X Close',
			enableStackAnimation: true,
			onBlurContainer: '.container',
			template: errorsText +
			'<div>' +							
			'<a href="#" target="_blank" class="twitter">Đóng</a>' +							
			'</div>'
		});
		$('#showEmptyTextSearch').trigger('click');
		return false;
	} else {
		return true;
	};
}
